
import pickle
import  json
class ShoppingSystem:
    def __init__(self,goods_info,sys_info):
        self.goods_info = goods_info
        self.sys_info = sys_info
        self.userdict = {}

    def load_user(self):
        file_name = self.sys_info + "_user.pickle"
        try:
            with open(file_name, "rb") as fp:
                self.userdict = pickle.load(fp)
        except:
            pass

    def register(self,name,passwd,init_amount):
        if name not in self.userdict:
            # 创建一个新用户、实例化User类
            user = User(name,passwd,init_amount)
            # 把名字作为key.user对象作为value，存在self.userdict里面
            # {"sc":user}
            self.userdict[name] = user
            # pickle的方式固化,可以固化对象和自己定义的函数
            file_name = self.sys_info + "_user.pickle"
            # b是二进制的意思，wb是以二进制打开的意思,而w是以文本的方式打开
            with open(file_name,"wb") as fp:
                # pickle是以二进制的形式写入的
                pickle.dump(self.userdict,fp)

    # 登录
    def login(self,name,passwd):
        # if name in self.userdict and self.userdict[name].passwd == passwd:
            count = 1
            # 用户可以试错三次
            while count <= 3:
                if name in self.userdict.keys():
                    if self.userdict[name].passwd == passwd:
                        print("登录成功")
                        break
                    else:
                        print("输入密码有误,请重新输入")
                        passwd = input("请重新输入密码")
                        count += 1
                else:
                    print("用户不存在，请注册")
                    break

    def check_goods(self):
        a=self.goods_info
        print("商品编号".center(8,),"商品名字".center(8,),"商品价格")
        for i in a.keys():
            print(i.center(10,),a[i]["name"].center(10,),a[i]["price"])

    def info_car(self,good_number,num):
        # 商品名
        # print(self.goods_info[good_number]["name"])
        good_name=self.goods_info[good_number]["name"]
        self.userdict[name].shopping_car[good_name] = self.goods_info[good_number]["price"]*int(num)
        print(self.userdict[name].shopping_car)

    def settle_car(self,name):
        sum = 0
        for i in self.userdict[name].shopping_car:
            sum += self.userdict[name].shopping_car[i]
        if int(self.userdict[name].init_amount) >= sum:
            self.userdict[name].init_amount =int(self.userdict[name].init_amount)-sum
            print(f"结算成功,您当前的余额是{self.userdict[name].init_amount}")
            self.userdict[name].shopping_car={}
        else:
            print("余额不足，请及时充值")
            print(f"您当前的余额为{self.userdict[name].init_amount},所需缴费为{sum}")
            settle_c = input("请输你是否清空购物车1.是 2.否 ")
            if settle_c == "1":
                self.userdict[name].shopping_car = {}
            else:
                print(f"你当前的购物车是：{self.userdict[name].shopping_car}")



class User:
    def __init__(self,name,passwd,init_amount):
        self.name = name
        self.passwd = passwd
        self.init_amount = init_amount
        self.shopping_car = {}

    def settle_accounts(self, money):
            self.init_amount -= money

fruit_goods = {
    "F01":{"name":"苹果","price":8},
    "F02":{"name":"香蕉","price":4},
}

medicine_goods = {
    "M01":{"name":"奥司他韦","price":65},
    "M02":{"name":"抗病毒口服液","price":30},
}
system1 = ShoppingSystem(fruit_goods,"水果购物系统")
system2 = ShoppingSystem(medicine_goods,"药店购物系统")

system = [system1,system2]

# 主程序：
while 1:
    print("当前平台，已有购物系统如下：")
    for k,v in enumerate(system):
        print(f"{k}.{v.sys_info}")
    c1 = input("请输入你的选择(按q退出):")
    if c1 == "q":
        break
    if c1.isdigit() and int(c1) < len(system):
        c1 = int(c1)
        current_system=system[c1]
        # 读取系统的信息
        current_system.load_user()
        print(f"欢迎进入{system[c1].sys_info}".center(40,"*"))
        while 1:
            c2 = input("1.登录\n2.注册\n请输入你的选择(按q退出)")
            if c2 == "q":
                break

            if c2 == "1":
                name,passwd= input("请输入你的名字、密码(用空白分割)").split()
                current_system.login(name,passwd)
                while 1:
                    c3 = input("1.查看商品\n2.添加购物车\n3.结算\n4.退出\n请输入你的选择：")
                    if c3 == "1":
                        current_system.check_goods()
                    if c3 == "2":
                        good_c, amount = input("请输入加入商品的编号、购买数量(用空白分割)").split()
                        current_system.info_car(good_c,amount)
                    if c3 == "3":
                        current_system.settle_car(name)
                    if c3 == "4":
                        break

            elif c2 == "2":
                name,passwd,init_amount = input("请输入你的名字、密码、和初始金额（用空白分割）").split()
                current_system.register(name,passwd,init_amount)

                print(f"当前系统用户有：{current_system.userdict[name]}")

            else:
                print("输入有误")
    else:
        print("输入有误，请重新输入!")